﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Controls;
using Caliburn.Micro;
using OI.Async;
using OI.DataModel;
using OI.Events;
using OI.Framework;
using OI.Views;

namespace OI.ViewModels
{
    [Export(typeof(CatalogViewModel))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class CatalogViewModel : DataGridScreenViewModelBase, IHandle<ChangeCatalogFilter>, IHandle<ChangeSearchText>
    {
        #region DATA
        public CategoryViewModel Categories { get; set; }
        public SourceViewModel Sources { get; set; }
        public List<OIDataset> ItemsAll { get; set; }
        readonly IEventAggregator Events;
        public DataGrid DetailsGrid { get; set; }

        // selected item in catalog
        public OIDataset CatalogItem
        {
            get 
            { 
                return _CatalogItem; 
            }
            set 
            {
                _CatalogItem = value;
                if (_CatalogItem != null && !OnSortColumn)
                {
                    Events.Publish(new SelectDataset()
                    {
                        DataSet = _CatalogItem
                    });
                }
            }
        }
        private OIDataset _CatalogItem;

        // search strings
        public string FreeformSearch { get; set; }
        public OICategory CategorySearch { get; set; }
        public OISource SourceSearch { get; set; }

        // datagrid contents filtered from ItemsAll
        public BindableCollection<OIDataset> Items
        {
            get
            {
                if (ItemsAll != null)
                {
                    string searchText = FreeformSearch == null ? null : FreeformSearch.ToLower();

                    var items = from r in ItemsAll
                                where ((string.IsNullOrEmpty(searchText) ||
                                       (r.Name.ToLower().IndexOf(searchText) != -1)) &&
                                        //r.Description.ToLower().IndexOf(searchText) != -1)) &&
                                       (CategorySearch == null || CategorySearch.ID == 0 || CategorySearch.ID == r.CategoryID) &&
                                       (SourceSearch == null || SourceSearch.ID == 0 || SourceSearch.Filter == r.SourceFilter) &&
                                       (!string.IsNullOrEmpty(r.TableName) || !string.IsNullOrEmpty(r.LayerID))
                                      )
                                select r;
                    return new BindableCollection<OIDataset>(items);
                }
                return null;
            }
        }
        #endregion

        [ImportingConstructor]
        public CatalogViewModel(IEventAggregator events)
		{
            Events = events;
			events.Subscribe(this);
		}

        
        // when the entire catalog is activated, load child view models for categories and sources
        protected override void OnActivate()
        {
            // set child views
            if (Categories == null)
            {
                Categories = IoC.Get<CategoryViewModel>();
            }
            if (Sources == null)
            {
                Sources = IoC.Get<SourceViewModel>();
            }

            // load datasets
            if (ItemsAll == null)
            {
                 Coroutine.BeginExecute(LoadDatasets());
            }
        }


        // called when the view loads
        protected override void  OnViewLoaded(object view)
        {
 	         base.OnViewLoaded(view);
             DetailsGrid = ((CatalogView)view).Details;
             DetailsGrid.SelectedIndex = -1;
        }


        // coroutine for async download of all datasets
        // we cache locally and filter client-side
        public IEnumerator<IResult> LoadDatasets()
        {
            Events.Publish(new ShowBusy { Caption = "loading datasets..." });

            var dsq = new CatalogQuery<OIDataset>(Configuration.Jurisdiction.ID);
            yield return dsq;

            ItemsAll = dsq.Results;
            NotifyOfPropertyChange(() => Items);

            Events.Publish(new HideBusy());
        }


        // receives message from category and source filter changes
        public void Handle(ChangeCatalogFilter message)
        {
            if (this.IsActive)
            {
                if (message.FilterType == ChangeCatalogFilter.Filter.Category)
                {
                    CategorySearch = message.FilterItem as OICategory;
                }
                else if (message.FilterType == ChangeCatalogFilter.Filter.Source)
                {
                    SourceSearch = message.FilterItem as OISource;
                }
                NotifyOfPropertyChange(() => Items);
            }
        }


        // receives message from freeform search panel
        public void Handle(ChangeSearchText message)
        {
            FreeformSearch = message.SearchString;
            NotifyOfPropertyChange(() => Items);
        }
    }
}
